import cv2
import os

def convert_to_binary_grayscale(input_folder, output_folder):
    # 确保输出文件夹存在
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 获取输入文件夹中的所有图片文件
    image_files = [f for f in os.listdir(input_folder) if f.endswith(('.jpg', '.jpeg', '.png', '.bmp'))]

    for image_file in image_files:
        # 读取图像
        image_path = os.path.join(input_folder, image_file)
        image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
        # image = cv2.imread(image_path)
        # image=cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        # 二值化处理
        # _, binary_image = cv2.threshold(image, 1, 1, cv2.THRESH_BINARY) #cv2.THRESH_BINARY：大于阈值的像素设置为最大值，小于等于阈值的像素设置为0。
        _, binary_image = cv2.threshold(image, 0, 1, cv2.THRESH_BINARY) #cv2.THRESH_BINARY：大于阈值的像素设置为最大值，小于等于阈值的像素设置为0。

        # 转换为三通道图像
        binary_image_3_channels = cv2.merge([binary_image, binary_image, binary_image])

        # 写入图像
        output_path = os.path.join(output_folder, image_file)
        cv2.imwrite(output_path, binary_image_3_channels)

        print(f"{image_file} 转换完成")

# # 指定输入文件夹和输出文件夹
# input_folder = "/home/jolly/develop/project/java/detection/src/main/resources/datasets/1/test_CDKC_UAV_verification/label"
# output_folder = "/home/jolly/develop/project/java/detection/src/main/resources/trainResult/233/test_CDKC_UAV_verification/label"
#
# # 执行转换
# convert_to_binary_grayscale(input_folder, output_folder)